<?php
//创建Server对象，监听 127.0.0.1:9501 端口。

require __DIR__ . '/../vendor/autoload.php';

// 引入 Composer 的自动加载文件




// 实例化应用
$app = (new think\App())->initialize();
$server = new Swoole\Server('0.0.0.0', 9500);
$server->set([
    'daemonize' => true, // 启用守护进程模式
    'log_file' => '../runtime/tcp.log', // 设置日志文件路径
    'heartbeat_check_interval' => 60, // 服务器定时检测在线列表的时间间隔（秒）
    'heartbeat_idle_time' => 120, // 连接最大的空闲时间（秒），默认是heartbeat_check_interval的两倍
]);
//监听连接进入事件。
$server->on('Connect', function ($server, $fd) {
    echo "Client: Connect.$fd\n";
});

//监听数据接收事件。
$server->on('Receive', function ($server, $fd, $reactor_id, $data) {
    $path=dir(getcwd())->path.'/serverlog/'.date('Ymd');
    if (! file_exists ( $path )) {
        mkdir ( "$path", 0777, true );
    }
    echo "Receive: $data.\n";
    echo "fd: $fd.\n";
    $indata=json_decode($data,true);

    if(is_array($indata)){
        if(array_key_exists("command",$indata)){
            if($indata["command"]=="open"){
                file_put_contents($path."/open.txt",date("Y-m-d H:i:s")."开门信息：".$indata["imei"]."\r\n",FILE_APPEND);
                $server->send($indata["fd"], '{"cmd":"onoff1"}');
                $server->send($fd, 'success');
            }

        }else if (array_key_exists("imei",$indata)){
            //注册包信息
            $imei=$indata["imei"];
            $deviceinfo=think\facade\Db::table("device")->where("imei",$indata["imei"])->find();
            if(empty($deviceinfo)){
                file_put_contents($path."/login.txt",date("Y-m-d H:i:s")."登录信息返回:\r\n".$imei."设备信息不存在\r\n",FILE_APPEND);
            }else {
                $add["imei"] = $imei;
                $add["fd"] = $fd;
                $add["device_id"] = $deviceinfo["id"];
                $add["community_id"] = $deviceinfo["community_id"];
                $add["create_time"] = date("Y-m-d H:i:s");
                $add["connect_status"] = "ON";
                \think\facade\Db::table("device_client_login")->where("imei", $imei)->delete();
                \think\facade\Db::table("device_client_login")->insert($add);
                $add_log["imei"] = $imei;
                $add_log["fd"] = $fd;
                $add_log["device_id"] = $deviceinfo["id"];
                $add_log["community_id"] = $deviceinfo["community_id"];
                $add_log["create_time"] = date("Y-m-d H:i:s");
                $add_log["device_name"] = $deviceinfo["lockname"];
                $add_log["type"] = "login";
                \think\facade\Db::table("device_client_login_logout_log")->insert($add_log);
            }
        }else{
//            echo "开闸: $imei\n";
//            $server->send($fd, '{"cmd":"onoff1"}');
        }
    }


});

//监听连接关闭事件。
$server->on('Close', function ($server, $fd) {
    $path=dir(getcwd())->path.'/serverlog/'.date('Ymd');
    file_put_contents($path."/close.txt",date("Y-m-d H:i:s").":$fd\r\n",FILE_APPEND);
    $clientinfo=\think\facade\Db::table("device_client_login")->where("fd", $fd)->find();
    if(!empty($clientinfo)){
        $deviceinfo=\think\facade\Db::table("device")->where("imei", $clientinfo["imei"])->find();
        \think\facade\Db::table("device_client_login")->where("fd", $fd)->delete();
        $add_log["imei"] = $deviceinfo["imei"];
        $add_log["fd"] = $fd;
        $add_log["device_id"] = $deviceinfo["id"];
        $add_log["community_id"] = $deviceinfo["community_id"];
        $add_log["create_time"] = date("Y-m-d H:i:s");
        $add_log["device_name"] = $deviceinfo["lockname"];
        $add_log["type"] = "logout";
        \think\facade\Db::table("device_client_login_logout_log")->insert($add_log);
    }

    echo "Client: Close.\n";
});

//启动服务器
$server->start();
